package com.by.config;

import org.springframework.web.filter.CharacterEncodingFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author LittleDesire
 * @description
 * @date 2022-03-25 周五 11:38
 * @since 17
 */
public class MyCharacterEncodingFilter extends CharacterEncodingFilter {

    public MyCharacterEncodingFilter(String utf) {
        super(utf);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String encoding = this.getEncoding();
        if (encoding != null) {
            if (this.isForceRequestEncoding() || request.getCharacterEncoding() == null) {
                request.setCharacterEncoding(encoding);
            }
            if (this.isForceResponseEncoding()) {
                //response.setContentType(String.format("text/html;charset=%s",encoding));
                response.setContentType(String.format("application/json;charset=%s", encoding));
                response.setCharacterEncoding(encoding);
            }
        }
        filterChain.doFilter(request, response);
    }
}
